package com.ars.listStatistics;

import com.ars.db.DBTools;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;

public class WebsiteResultsStatistics {

    private int wid = 0;

    public LineChart<String, Number> getLineChart(String websitename) {

        final CategoryAxis xAxis = new CategoryAxis();
        final NumberAxis yAxis = new NumberAxis();
        xAxis.setLabel("月份");
        yAxis.setLabel("金额");
        final LineChart<String, Number> lineChart = new LineChart<String, Number>(xAxis, yAxis);

        lineChart.setTitle(websitename + "网点6个月业务统计");

        // defining a series
        XYChart.Series series = new XYChart.Series();
        series.setName("网点营业额");
        DBTools p = new DBTools();
        String sql2 = "select wid from website where name='" + websitename + "'";
        ResultSet rs1 = p.query(sql2);
        try {
            while (rs1.next()) {
                wid = rs1.getInt("wid");
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
        }

        // 获取当前的年份，月份
        Calendar date = Calendar.getInstance();
        int year = date.get(Calendar.YEAR);
        int month = date.get(Calendar.MONTH) + 1;

        //ArrayList<XYChart.Data>这个数组用来处理6个点
        ArrayList<XYChart.Data> points = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            XYChart.Data<String, Number> point = null;
            try {
                //new XYChart.Data(月份，营业额)
                //(month<10)?"0"+month:""+month表示：处理小于10的月份前加0
                point = new XYChart.Data((month < 10) ? "0" + month : "" + month, new Turnover().getTurnover(wid, year, month));
            } catch (SQLException e) {
                e.printStackTrace();
            }
            month--;
            if (month < 1) {//处理小于1的月份，年份将推到上一年
                year--;
                month += 12;
            }
            points.add(point);
        }
        for (int i = points.size(); i > 0; i--) {//将每一个点的数据添加到图表中
            series.getData().add(points.get(i - 1));
        }


        lineChart.getData().add(series);
        return lineChart;
    }

}
